// import React, { useState } from 'react';
// import axios from 'axios';

// interface PrizeForm {
//   prize_name: string;
//   prize_description: string;
//   points: string;
//   stock: string;
// }

// const Prize: React.FC = () => {
//   const [form, setForm] = useState<PrizeForm>({
//     prize_name: '',
//     prize_description: '',
//     points: '',
//     stock: ''
//   });
//   const [prizeImageFile, setPrizeImageFile] = useState<File | null>(null);
//   const [previewUrl, setPreviewUrl] = useState<string>('');
//   const [message, setMessage] = useState<string>('');
//   const [loading, setLoading] = useState<boolean>(false);

//   const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
//     setForm({
//       ...form,
//       [e.target.name]: e.target.value
//     });
//   };

//   const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const file = e.target.files?.[0];
//     if (file) {
//       setPrizeImageFile(file);
//       setPreviewUrl(URL.createObjectURL(file));
//     } else {
//       setPrizeImageFile(null);
//       setPreviewUrl('');
//     }
//   };

//   const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
//     e.preventDefault();

//     if (!prizeImageFile) {
//       setMessage('请上传奖品图片');
//       return;
//     }
//     if (!form.prize_name || !form.points || !form.stock) {
//       setMessage('请填写所有必填字段');
//       return;
//     }

//     const formData = new FormData();
//     formData.append('prize_image', prizeImageFile);
//     formData.append('prize_name', form.prize_name);
//     formData.append('prize_description', form.prize_description);
//     formData.append('points', form.points);
//     formData.append('stock', form.stock);

//     try {
//       setLoading(true);
//       setMessage('上传中...');
//       const res = await axios.post('http://localhost:5000/api/addPrize', formData, {
//         headers: { 'Content-Type': 'multipart/form-data' }
//       });
//       setMessage('添加成功，奖品ID：' + res.data.id);
//       setForm({ prize_name: '', prize_description: '', points: '', stock: '' });
//       setPrizeImageFile(null);
//       setPreviewUrl('');
//     } catch (err: unknown) {
//       if (axios.isAxiosError(err)) {
//         setMessage('上传失败: ' + (err.response?.data?.message || err.message));
//       } else {
//         setMessage('上传失败: 未知错误');
//       }
//     } finally {
//       setLoading(false);
//     }
//   };

//   return (
//     <div style={{ maxWidth: 500, margin: '20px auto' }}>
//       <h2>添加奖品</h2>
//       <form onSubmit={handleSubmit}>
//         <div>
//           <label>奖品图片*：</label><br />
//           {previewUrl && (
//             <img
//               src={previewUrl}
//               alt="预览"
//               style={{ width: 150, height: 150, objectFit: 'cover', marginBottom: 10 }}
//             />
//           )}
//           <input type="file" accept="image/*" onChange={handleFileChange} disabled={loading} />
//         </div>
//         <div>
//           <label>奖品名称*：</label><br />
//           <input
//             type="text"
//             name="prize_name"
//             value={form.prize_name}
//             onChange={handleChange}
//             required
//           />
//         </div>
//         <div>
//           <label>奖品介绍：</label><br />
//           <textarea
//             name="prize_description"
//             value={form.prize_description}
//             onChange={handleChange}
//           />
//         </div>
//         <div>
//           <label>积分*：</label><br />
//           <input
//             type="number"
//             name="points"
//             value={form.points}
//             onChange={handleChange}
//             required
//           />
//         </div>
//         <div>
//           <label>库存*：</label><br />
//           <input
//             type="number"
//             name="stock"
//             value={form.stock}
//             onChange={handleChange}
//             required
//           />
//         </div>
//         <button type="submit" disabled={loading}>
//           {loading ? '上传中...' : '添加奖品'}
//         </button>
//       </form>
//       {message && <p style={{ marginTop: 10 }}>{message}</p>}
//     </div>
//   );
// };

// export default Prize;




import React, { useState } from 'react';
import { Form, Input, InputNumber, Upload, Button, message, Card } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import axios from 'axios';

interface PrizeForm {
  prize_name: string;
  prize_description: string;
  points: number;
  stock: number;
}

const Prize: React.FC = () => {
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState<any[]>([]);
  const [previewUrl, setPreviewUrl] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);

  const handleUploadChange = (info: any) => {
    const file = info.file.originFileObj;
    setFileList(info.fileList);

    if (file) {
      const url = URL.createObjectURL(file);
      setPreviewUrl(url);
    } else {
      setPreviewUrl('');
    }
  };

  const handleSubmit = async (values: PrizeForm) => {
    if (fileList.length === 0) {
      message.error('请上传奖品图片');
      return;
    }

    const formData = new FormData();
    formData.append('prize_image', fileList[0].originFileObj);
    formData.append('prize_name', values.prize_name);
    formData.append('prize_description', values.prize_description || '');
    formData.append('points', values.points.toString());
    formData.append('stock', values.stock.toString());

    try {
      setLoading(true);
      const res = await axios.post('http://localhost:5000/api/addPrize', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      });
      message.success(`添加成功，奖品ID：${res.data.id}`);
      form.resetFields();
      setFileList([]);
      setPreviewUrl('');
    } catch (error: any) {
      message.error(`上传失败: ${error?.response?.data?.message || error.message}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card title="添加奖品" style={{ maxWidth: 600, margin: '40px auto' }}>
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        initialValues={{
          prize_name: '',
          prize_description: '',
          points: 0,
          stock: 0
        }}
      >
        <Form.Item label="奖品图片*" required>
          <Upload
            beforeUpload={() => false}
            fileList={fileList}
            onChange={handleUploadChange}
            accept="image/*"
            listType="picture"
            maxCount={1}
          >
            <Button icon={<UploadOutlined />} disabled={loading}>
              选择图片
            </Button>
          </Upload>
          {previewUrl && (
            <img
              src={previewUrl}
              alt="预览"
              style={{ marginTop: 10, width: 120, height: 120, objectFit: 'cover', borderRadius: 4 }}
            />
          )}
        </Form.Item>

        <Form.Item
          label="奖品名称*"
          name="prize_name"
          rules={[{ required: true, message: '请输入奖品名称' }]}
        >
          <Input disabled={loading} />
        </Form.Item>

        <Form.Item label="奖品介绍" name="prize_description">
          <Input.TextArea rows={3} disabled={loading} />
        </Form.Item>

        <Form.Item
          label="积分*"
          name="points"
          rules={[{ required: true, message: '请输入兑换所需积分' }]}
        >
          <InputNumber min={0} className="w-full" disabled={loading} />
        </Form.Item>

        <Form.Item
          label="库存*"
          name="stock"
          rules={[{ required: true, message: '请输入库存数量' }]}
        >
          <InputNumber min={0} className="w-full" disabled={loading} />
        </Form.Item>

        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            loading={loading}
            block
          >
            添加奖品
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default Prize;
